<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<meta name="referrer" content="same-origin">
<meta name="referrer" content="no-referrer" />








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Netty之旅," />










<meta name="description" content="&amp;emsp;&amp;emsp;Netty之旅（五）ByteBuf内存管理之PoolSubpage中描述PoolSubpage分配内存的时候，allocateSubpage方法开头就会调用PoolArena：1234private long allocateSubpage(int normCapacity) &amp;#123;    PoolSubpage&amp;lt;T&amp;gt; head = arena.findS">
<meta name="keywords" content="Netty之旅">
<meta property="og:type" content="article">
<meta property="og:title" content="Netty之旅（六）ByteBuf内存管理之PoolArena">
<meta property="og:url" content="http://yoursite.com/2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/index.html">
<meta property="og:site_name" content="矩阵编程">
<meta property="og:description" content="&amp;emsp;&amp;emsp;Netty之旅（五）ByteBuf内存管理之PoolSubpage中描述PoolSubpage分配内存的时候，allocateSubpage方法开头就会调用PoolArena：1234private long allocateSubpage(int normCapacity) &amp;#123;    PoolSubpage&amp;lt;T&amp;gt; head = arena.findS">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-24T16:22:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Netty之旅（六）ByteBuf内存管理之PoolArena">
<meta name="twitter:description" content="&amp;emsp;&amp;emsp;Netty之旅（五）ByteBuf内存管理之PoolSubpage中描述PoolSubpage分配内存的时候，allocateSubpage方法开头就会调用PoolArena：1234private long allocateSubpage(int normCapacity) &amp;#123;    PoolSubpage&amp;lt;T&amp;gt; head = arena.findS">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/"/>





  <title>Netty之旅（六）ByteBuf内存管理之PoolArena | 矩阵编程</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7d29e6fba8e07d1a8af2414a20e5f2a6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">矩阵编程</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-主页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-主页"></i> <br />
            
            主页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-分类"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-所有文章">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-文章"></i> <br />
            
            所有文章
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="matrix">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="矩阵编程">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Netty之旅（六）ByteBuf内存管理之PoolArena</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-08T21:28:46+08:00">
                2018-08-08
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Netty之旅/" itemprop="url" rel="index">
                    <span itemprop="name">Netty之旅</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>&emsp;&emsp;<a href="../Netty之旅（五）ByteBuf内存管理之PoolSubpage">Netty之旅（五）ByteBuf内存管理之PoolSubpage</a>中描述PoolSubpage分配内存的时候，allocateSubpage方法开头就会调用PoolArena：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">long</span> <span class="title">allocateSubpage</span><span class="params">(<span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">    PoolSubpage&lt;T&gt; head = arena.findSubpagePoolHead(normCapacity);</span><br><span class="line">    ......（省略）</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>或者在<a href="../Netty之旅（三）ByteBuf内存管理">Netty之旅（三）ByteBuf内存管理</a>中，PooledByteBufAllocator来分配堆内存：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) &#123;</span><br><span class="line">    PoolThreadCache cache = threadCache.get();</span><br><span class="line">    PoolArena&lt;byte[]&gt; heapArena = cache.heapArena;</span><br><span class="line">    ......（省略）</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<p>为什么还是PoolArena？由于PoolSubpage的存在，整个Chunk被分成了更加碎片化的小内存，当分配大内存的时候，很可能会因为小内存的分配占用，导致无法找到连续的大段内存来进行分配。不过PoolArena的出现，这些问题都迎刃而解了。<br>&emsp;&emsp;PoolArena的设计借鉴了jemalloc内存分配，下面是内部的骨架：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">......（省略部分）</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolSubpage&lt;T&gt;[] tinySubpagePools;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolSubpage&lt;T&gt;[] smallSubpagePools;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; q050;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; q025;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; q000;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; qInit;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; q075;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> PoolChunkList&lt;T&gt; q100;</span><br><span class="line">......（省略部分）</span><br></pre></td></tr></table></figure></p>
<ol>
<li>tinySubpagePools和smallSubpagePools都是PoolSubpage结构，其中tinySubpagePools分配小于512字节的内存，smallSubpagePools用于分配大于等于512字节的内存（注意PoolSubpage小于一页）。</li>
<li>PoolChunkList将PoolChunk按利用率拆分，这种形式的拆分极大保障了内存分配的成功率，下面是各个PoolChunkList的含义：<ul>
<li><strong>qInit：</strong>内存利用率0-25%的chunk链。</li>
<li><strong>q000：</strong>内存利用率1-50%的chunk链。</li>
<li><strong>q025：</strong>内存利用率25-75%的chunk链。</li>
<li><strong>q050：</strong>内存利用率50-100%个chunk链。</li>
<li><strong>q075：</strong>内存利用率75-100%个chunk链。</li>
<li><strong>q100：</strong>内存利用率100%chunk链。</li>
</ul>
</li>
</ol>
<h3 id="小内存分配"><a href="#小内存分配" class="headerlink" title="小内存分配"></a>小内存分配</h3><p>&emsp;&emsp;看一下tinySubpagePools和smallSubpagePools数组是如何初始化的：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// numTinySubpagePools 为512 &gt;&gt;&gt; 4 = 32</span></span><br><span class="line">tinySubpagePools = newSubpagePoolArray(numTinySubpagePools);</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; tinySubpagePools.length; i ++) &#123;</span><br><span class="line">    tinySubpagePools[i] = newSubpagePoolHead(pageSize);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// pageShifts默认为13所以numSmallSubpagePools=4</span></span><br><span class="line">numSmallSubpagePools = pageShifts - <span class="number">9</span>;</span><br><span class="line">smallSubpagePools = newSubpagePoolArray(numSmallSubpagePools);</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; smallSubpagePools.length; i ++) &#123;</span><br><span class="line">    smallSubpagePools[i] = newSubpagePoolHead(pageSize);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>newSubpagePoolHead()</strong>函数很简单，新建了一个PoolSubpage，并且他内部前置后置指针都指向自身<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> PoolSubpage&lt;T&gt; <span class="title">newSubpagePoolHead</span><span class="params">(<span class="keyword">int</span> pageSize)</span> </span>&#123;</span><br><span class="line">        PoolSubpage&lt;T&gt; head = <span class="keyword">new</span> PoolSubpage&lt;T&gt;(pageSize);</span><br><span class="line">        head.prev = head;</span><br><span class="line">        head.next = head;</span><br><span class="line">        <span class="keyword">return</span> head;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>好的，继续看一下PoolArena如何分配小内存：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">allocate</span><span class="params">(PoolThreadCache cache, PooledByteBuf&lt;T&gt; buf, <span class="keyword">final</span> <span class="keyword">int</span> reqCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> normCapacity = normalizeCapacity(reqCapacity);</span><br><span class="line">    <span class="keyword">if</span> (isTinyOrSmall(normCapacity)) &#123; <span class="comment">// capacity &lt; pageSize</span></span><br><span class="line">        <span class="keyword">int</span> tableIdx;</span><br><span class="line">        PoolSubpage&lt;T&gt;[] table;</span><br><span class="line">        <span class="keyword">boolean</span> tiny = isTiny(normCapacity);</span><br><span class="line">        <span class="keyword">if</span> (tiny) &#123; <span class="comment">// &lt; 512</span></span><br><span class="line">            <span class="keyword">if</span> (cache.allocateTiny(<span class="keyword">this</span>, buf, reqCapacity, normCapacity)) &#123;</span><br><span class="line">                <span class="comment">// was able to allocate out of the cache so move on</span></span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            tableIdx = tinyIdx(normCapacity);</span><br><span class="line">            table = tinySubpagePools;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (cache.allocateSmall(<span class="keyword">this</span>, buf, reqCapacity, normCapacity)) &#123;</span><br><span class="line">                <span class="comment">// was able to allocate out of the cache so move on</span></span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            tableIdx = smallIdx(normCapacity);</span><br><span class="line">            table = smallSubpagePools;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> PoolSubpage&lt;T&gt; head = table[tableIdx];</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * Synchronize on the head. This is needed as &#123;<span class="doctag">@link</span> PoolChunk#allocateSubpage(int)&#125; and</span></span><br><span class="line"><span class="comment">         * &#123;<span class="doctag">@link</span> PoolChunk#free(long)&#125; may modify the doubly linked list as well.</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">synchronized</span> (head) &#123;</span><br><span class="line">            <span class="keyword">final</span> PoolSubpage&lt;T&gt; s = head.next;</span><br><span class="line">            <span class="comment">// 初始化s=head</span></span><br><span class="line">            <span class="keyword">if</span> (s != head) &#123;</span><br><span class="line">                <span class="keyword">assert</span> s.doNotDestroy &amp;&amp; s.elemSize == normCapacity;</span><br><span class="line">                <span class="keyword">long</span> handle = s.allocate();</span><br><span class="line">                <span class="keyword">assert</span> handle &gt;= <span class="number">0</span>;</span><br><span class="line">                s.chunk.initBufWithSubpage(buf, handle, reqCapacity);</span><br><span class="line">                incTinySmallAllocation(tiny);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            allocateNormal(buf, reqCapacity, normCapacity);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        incTinySmallAllocation(tiny);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// ......（省略下面分配大内存的代码）......</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;小内存分配和jemalloc一样先使用Thread Cache进行分配，Thread Cache初始无法分配内存，直接使用tinySubpagePools或者smallSubpagePools数组分配，两者操作近似，看一下索引函数：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// normCapacity最小16字节，最大512，32个数组映射</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">tinyIdx</span><span class="params">(<span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">    eturn normCapacity &gt;&gt;&gt; <span class="number">4</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// normCapacity大于512，小于8192，4个数组映射</span></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">smallIdx</span><span class="params">(<span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> tableIdx = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">int</span> i = normCapacity &gt;&gt;&gt; <span class="number">10</span>;</span><br><span class="line">    <span class="keyword">while</span> (i != <span class="number">0</span>) &#123;</span><br><span class="line">        i &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        tableIdx ++;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> tableIdx;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>根据索引拿到数组中对应的PoolSubpage，先查看PoolSubpage的next指针，从上面可知初始next指针就是它自身，该PoolSubpage无法分配内存。一路往下，方法栈会进入<strong>allocateNormal()</strong>使用PoolChunkList分配内存。</p>
<h3 id="大内存分配"><a href="#大内存分配" class="headerlink" title="大内存分配"></a>大内存分配</h3><p>探究<strong>allocateNormal()</strong>如何分配内存之前，先看一下PoolArena内部PoolChunkList的关系，参照PoolArena的构造函数：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">q100 = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, <span class="keyword">null</span>, <span class="number">100</span>, Integer.MAX_VALUE, chunkSize);</span><br><span class="line">q075 = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, q100, <span class="number">75</span>, <span class="number">100</span>, chunkSize);</span><br><span class="line">q050 = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, q075, <span class="number">50</span>, <span class="number">100</span>, chunkSize);</span><br><span class="line">q025 = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, q050, <span class="number">25</span>, <span class="number">75</span>, chunkSize);</span><br><span class="line">q000 = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, q025, <span class="number">1</span>, <span class="number">50</span>, chunkSize);</span><br><span class="line">qInit = <span class="keyword">new</span> PoolChunkList&lt;T&gt;(<span class="keyword">this</span>, q000, Integer.MIN_VALUE, <span class="number">25</span>, chunkSize);</span><br><span class="line"></span><br><span class="line">q100.prevList(q075);</span><br><span class="line">q075.prevList(q050);</span><br><span class="line">q050.prevList(q025);</span><br><span class="line">q025.prevList(q000);</span><br><span class="line">q000.prevList(<span class="keyword">null</span>);</span><br><span class="line">qInit.prevList(qInit);</span><br></pre></td></tr></table></figure></p>
<p>以及PoolChunkList自身的结构：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">private final PoolArena&lt;T&gt; arena;</span><br><span class="line">private final PoolChunkList&lt;T&gt; nextList;</span><br><span class="line">private final int minUsage;</span><br><span class="line">private final int maxUsage;</span><br><span class="line">private final int maxCapacity;</span><br><span class="line">private PoolChunk&lt;T&gt; head;</span><br><span class="line"></span><br><span class="line">// This is only update once when create the linked like list of PoolChunkList in PoolArena constructor.</span><br><span class="line">private PoolChunkList&lt;T&gt; prevList;</span><br><span class="line">    PoolChunkList(PoolArena&lt;T&gt; arena, PoolChunkList&lt;T&gt; nextList, int minUsage, int maxUsage, int chunkSize) &#123;</span><br><span class="line">    assert minUsage &lt;= maxUsage;</span><br><span class="line">    this.arena = arena;</span><br><span class="line">    this.nextList = nextList;</span><br><span class="line">    this.minUsage = minUsage;</span><br><span class="line">    this.maxUsage = maxUsage;</span><br><span class="line">    maxCapacity = calculateMaxCapacity(minUsage, chunkSize);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以画出这样的链式结构：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">+-------+   +------+    +------+    +------+    +------+    +------+</span><br><span class="line">| qInit |--&gt;| q000 |&lt;--&gt;| q025 |&lt;--&gt;| q050 |&lt;--&gt;| q075 |&lt;--&gt;| q100 |</span><br><span class="line">+-------+   +------+    +------+    +------+    +------+    +------+</span><br><span class="line">qInit的前置节点为自身</span><br><span class="line">q100无前置节点</span><br></pre></td></tr></table></figure></p>
<p>上面看了PoolArena分配小内存的场景，再看下他如何分配大内存：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">private void allocate(PoolThreadCache cache, PooledByteBuf&lt;T&gt; buf, final int reqCapacity) &#123;</span><br><span class="line">    // ......（省略上面分配小内存的代码）......</span><br><span class="line">    if (normCapacity &lt;= chunkSize) &#123;</span><br><span class="line">        if (cache.allocateNormal(this, buf, reqCapacity, normCapacity)) &#123;</span><br><span class="line">            // was able to allocate out of the cache so move on</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        synchronized (this) &#123;</span><br><span class="line">            allocateNormal(buf, reqCapacity, normCapacity);</span><br><span class="line">            ++allocationsNormal;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // Huge allocations are never served via the cache so just call allocateHuge</span><br><span class="line">        allocateHuge(buf, reqCapacity);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>大内存分配会分为小于等于一个Chunk（一个PoolChunk能分配的最大内存）的内存和大于一个chunk的内存两种情况。如果是小于等于一个Chunk的内存，依然是先去Thread Cache尝试分配，如果没有，使用<strong>allocateNormal</strong>函数进行分配，这和小内存分配的情况是一致的。<strong>allocateHuge</strong>是分配非池化内存，也没有线程缓存，不说了。直接看<strong>allocateNormal</strong>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">allocateNormal</span><span class="params">(PooledByteBuf&lt;T&gt; buf, <span class="keyword">int</span> reqCapacity, <span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) ||</span><br><span class="line">            q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) ||</span><br><span class="line">            q075.allocate(buf, reqCapacity, normCapacity)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Add a new chunk.</span></span><br><span class="line">        PoolChunk&lt;T&gt; c = newChunk(pageSize, maxOrder, pageShifts, chunkSize);</span><br><span class="line">        <span class="keyword">long</span> handle = c.allocate(normCapacity);</span><br><span class="line">        <span class="keyword">assert</span> handle &gt; <span class="number">0</span>;</span><br><span class="line">        c.initBuf(buf, handle, reqCapacity);</span><br><span class="line">        qInit.add(c);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li><p>使用PoolChunkList分配内存，分配内存按照下面的次序：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">q050--&gt;q025--&gt;q000--&gt;qInit--&gt;q075</span><br></pre></td></tr></table></figure>
</li>
<li><p>如果这几个PoolChunkList都无法分配内存，新建一个PoolChunk并加入到qInit中。</p>
</li>
<li>实际分配内存的地方，还是PoolChunk</li>
</ol>
<p>贴一下PoolChunkList分配内存的方法：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">allocate</span><span class="params">(PooledByteBuf&lt;T&gt; buf, <span class="keyword">int</span> reqCapacity, <span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (head == <span class="keyword">null</span> || normCapacity &gt; maxCapacity) &#123;</span><br><span class="line">            <span class="comment">// Either this PoolChunkList is empty or the requested capacity is larger then the capacity which can</span></span><br><span class="line">            <span class="comment">// be handled by the PoolChunks that are contained in this PoolChunkList.</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (PoolChunk&lt;T&gt; cur = head;;) &#123;</span><br><span class="line">            <span class="keyword">long</span> handle = cur.allocate(normCapacity);</span><br><span class="line">            <span class="keyword">if</span> (handle &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                cur = cur.next;</span><br><span class="line">                <span class="keyword">if</span> (cur == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                cur.initBuf(buf, handle, reqCapacity);</span><br><span class="line">                <span class="keyword">if</span> (cur.usage() &gt;= maxUsage) &#123;</span><br><span class="line">                    remove(cur);</span><br><span class="line">                    nextList.add(cur);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看出，PoolChunkList中有一个PoolChunk队列分配内存，如果某个PoolChunk的内存的使用率大于当前PoolChunkList最大的内存使用率，该PoolChunk就会被移除并加入下一个q中。</p>
<h3 id="PoolSubpage再整理"><a href="#PoolSubpage再整理" class="headerlink" title="PoolSubpage再整理"></a>PoolSubpage再整理</h3><p><a href="../Netty之旅（五）ByteBuf内存管理之PoolSubpage">Netty之旅（五）ByteBuf内存管理之PoolSubpage</a>中已经分析过PoolChunk分配小内存的方法，再贴一下<strong>allocateSubpage</strong>代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">long</span> <span class="title">allocateSubpage</span><span class="params">(<span class="keyword">int</span> normCapacity)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it.</span></span><br><span class="line">    <span class="comment">// This is need as we may add it back and so alter the linked-list structure.</span></span><br><span class="line">    PoolSubpage&lt;T&gt; head = arena.findSubpagePoolHead(normCapacity);</span><br><span class="line">    <span class="keyword">synchronized</span> (head) &#123;</span><br><span class="line">        <span class="keyword">int</span> d = maxOrder; <span class="comment">// subpages are only be allocated from pages i.e., leaves</span></span><br><span class="line">        <span class="keyword">int</span> id = allocateNode(d);</span><br><span class="line">        <span class="keyword">if</span> (id &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> id;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> PoolSubpage&lt;T&gt;[] subpages = <span class="keyword">this</span>.subpages;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> pageSize = <span class="keyword">this</span>.pageSize;</span><br><span class="line"></span><br><span class="line">        freeBytes -= pageSize;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> subpageIdx = subpageIdx(id);</span><br><span class="line">        PoolSubpage&lt;T&gt; subpage = subpages[subpageIdx];</span><br><span class="line">        <span class="keyword">if</span> (subpage == <span class="keyword">null</span>) &#123;</span><br><span class="line">            subpage = <span class="keyword">new</span> PoolSubpage&lt;T&gt;(head, <span class="keyword">this</span>, id, runOffset(id), pageSize, normCapacity);</span><br><span class="line">            subpages[subpageIdx] = subpage;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            subpage.init(head, normCapacity);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> subpage.allocate();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// subpage.init会调用此方法</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addToPool</span><span class="params">(PoolSubpage&lt;T&gt; head)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">assert</span> prev == <span class="keyword">null</span> &amp;&amp; next == <span class="keyword">null</span>;</span><br><span class="line">    prev = head;</span><br><span class="line">    next = head.next;</span><br><span class="line">    next.prev = <span class="keyword">this</span>;</span><br><span class="line">    head.next = <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>开头arena.findSubpagePoolHead没有深究，现在回过头再来看看，小内存分配，由arena中tinySubpagePools或smallSubpagePools数组开始，根据分配内存的大小指定不同的数组和数组索引，初始拿到数组中的PoolSubpage因为head.next=next是无法直接分配内存的，会跟大内存分配方式一样，新建PoolChunk，PoolChunk内部会实例化一个PoolSubpage数组并选取一个PoolSubpage来分配内存，同时将此PoolSubpage链接到tinySubpagePools或smallSubpagePools数组的元素（参照addToPool方法），后续就可以使用这个PoolSubpage来分配内存了。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">tinySubpagePools</span><br><span class="line">或smallSubpagePools数组</span><br><span class="line">+-------------+</span><br><span class="line">|    head     |</span><br><span class="line">|             |&lt;--&gt;PoolSubpage</span><br><span class="line">| PoolSubpage |</span><br><span class="line">+-------------+</span><br><span class="line">|    head     |</span><br><span class="line">|             |&lt;--&gt;head</span><br><span class="line">| PoolSubpage |</span><br><span class="line">+-------------+</span><br><span class="line">|    head     |</span><br><span class="line">|             |&lt;--&gt;head</span><br><span class="line">| PoolSubpage |</span><br><span class="line">+-------------+</span><br><span class="line">|    head     |</span><br><span class="line">|             |&lt;--&gt;head</span><br><span class="line">| PoolSubpage |</span><br><span class="line">+-------------+</span><br></pre></td></tr></table></figure></p>
<h3 id="Thread-Cache"><a href="#Thread-Cache" class="headerlink" title="Thread Cache"></a>Thread Cache</h3><p>&emsp;&emsp;Thread Cache就一个类，<strong>PoolThreadCache</strong>，内部有三种分配方式，分别为tiny、small、normal：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Hold the caches for the different size classes, which are tiny, small and normal.</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;<span class="keyword">byte</span>[]&gt;[] tinySubPageHeapCaches;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;<span class="keyword">byte</span>[]&gt;[] smallSubPageHeapCaches;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;ByteBuffer&gt;[] tinySubPageDirectCaches;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;ByteBuffer&gt;[] smallSubPageDirectCaches;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;<span class="keyword">byte</span>[]&gt;[] normalHeapCaches;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> MemoryRegionCache&lt;ByteBuffer&gt;[] normalDirectCaches;</span><br></pre></td></tr></table></figure></p>
<p>tinyCache数组大小32，包含容量512的PoolChunk队列；smallCache数组大小4，包含容量256的PoolChunk队列；normalCache数组大小12，包含容量64的PoolChunk队列</p>
<p>下面按照几个问题来探究<strong>PoolThreadCache</strong>：</p>
<ol>
<li><p><strong>何时加入缓存？</strong><br> 当PoolArena调用free函数释放内存的的时候：</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">free</span><span class="params">(PoolChunk&lt;T&gt; chunk, <span class="keyword">long</span> handle, <span class="keyword">int</span> normCapacity, PoolThreadCache cache)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (chunk.unpooled) &#123;</span><br><span class="line">            <span class="keyword">int</span> size = chunk.chunkSize();</span><br><span class="line">            destroyChunk(chunk);</span><br><span class="line">            activeBytesHuge.add(-size);</span><br><span class="line">            deallocationsHuge.increment();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            SizeClass sizeClass = sizeClass(normCapacity);</span><br><span class="line">            <span class="keyword">if</span> (cache != <span class="keyword">null</span> &amp;&amp; cache.add(<span class="keyword">this</span>, chunk, handle, normCapacity, sizeClass)) &#123;</span><br><span class="line">                <span class="comment">// cached so not free it.</span></span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            freeChunk(chunk, handle, sizeClass);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p> cache会按照normCapacity的尺寸来分别缓存tiny/small/normal。</p>
</li>
<li><p><strong>如何从缓存中分配内存</strong><br> 上面说缓存的是PoolChunk队列其实不准确，看一下MemoryRegionCache的结构：</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">abstract</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">MemoryRegionCache</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> size;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Entry&lt;T&gt;&gt; queue;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> SizeClass sizeClass;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> allocations;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Entry</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">        <span class="keyword">final</span> Handle&lt;Entry&lt;?&gt;&gt; recyclerHandle;</span><br><span class="line">        PoolChunk&lt;T&gt; chunk;</span><br><span class="line">        <span class="keyword">long</span> handle = -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> Entry其实是PoolChunk+handle的结构，cache分配内存的时候可以很方便地依据PoolChunk+handle组合来获取原来已经分配过的ByteBuf的内存空间：</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">boolean</span> <span class="title">allocate</span><span class="params">(PooledByteBuf&lt;T&gt; buf, <span class="keyword">int</span> reqCapacity)</span> </span>&#123;</span><br><span class="line">    Entry&lt;T&gt; entry = queue.poll();</span><br><span class="line">    <span class="keyword">if</span> (entry == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    initBuf(entry.chunk, entry.handle, buf, reqCapacity);</span><br><span class="line">    entry.recycle();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// allocations is not thread-safe which is fine as this is only called from the same thread all time.</span></span><br><span class="line">    ++ allocations;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>何时释放缓存</strong></p>
<ol>
<li>在线程销毁的时候</li>
<li>确保万一，PoolThreadCache在finalize()的时候也会尝试释放内存</li>
<li>allocate的时候，当分配次数达到freeSweepAllocationThreshold这个阈值，去检测队列，释放空闲的内存空间</li>
</ol>
</li>
</ol>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Netty之旅/" rel="tag"># Netty之旅</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/08/Netty之旅（五）ByteBuf内存管理之PoolSubpage/" rel="next" title="Netty之旅（五）ByteBuf内存管理之PoolSubpage">
                <i class="fa fa-chevron-left"></i> Netty之旅（五）ByteBuf内存管理之PoolSubpage
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/18/RocketMQ之旅（一）概述/" rel="prev" title="RocketMQ之旅（一）概述">
                RocketMQ之旅（一）概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">matrix</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">47</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#小内存分配"><span class="nav-number">1.</span> <span class="nav-text">小内存分配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#大内存分配"><span class="nav-number">2.</span> <span class="nav-text">大内存分配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PoolSubpage再整理"><span class="nav-number">3.</span> <span class="nav-text">PoolSubpage再整理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Thread-Cache"><span class="nav-number">4.</span> <span class="nav-text">Thread Cache</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">matrix</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>
<div class=BbeiAn-info">
  浙ICP备 -
  <a href="http://www.beian.miit.gov.cn">18040498号</a>
  </a>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://luyun.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://yoursite.com/2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/';
          this.page.identifier = '2018/08/08/Netty之旅（六）ByteBuf内存管理之PoolArena/';
          this.page.title = 'Netty之旅（六）ByteBuf内存管理之PoolArena';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://luyun.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
